package su.jiedai.module;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import su.jiedai.dto.JiedaiDto;
import su.jiedai.entity.JiedaiEntity;
import su.jiedai.service.IJiedaiService;
import su.tool.SuDateUtils;
import su.tool.SuDoubleUtils;
import su.tool.SuIntUtils;
import su.tool.excel.ExcelUtil;
/**
 * 金科力_借货信息管理
 * @author SuShimeng
 *
 */
@Controller
@RequestMapping("/jiedai")
public class JiedaiServlet {

	@Autowired
	private IJiedaiService jiedaiService;

	protected final Log log = LogFactory.getLog(getClass());
	/**
	 * 借贷信息首页
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("index")
	public String index(HttpServletRequest request, Model model) throws Exception {
		int jdId = SuIntUtils.getInt(request.getParameter("jdId"));
		if(jdId != 0){
			JiedaiEntity baseinfo = jiedaiService.getJiedaiById(jdId);
			model.addAttribute("baseinfo", baseinfo);
		}
//		String year = request.getParameter("year");
//		if(StringUtils.isBlank(year))year="2012";
		List<JiedaiEntity> jiedais = jiedaiService.getAll(null);
		model.addAttribute("list", jiedais);
		return "/maintain/jiedai/jiedai_index";
	}
	
	/**
	 * 保存
	 * @param request
	 * @param model
	 * @param jiedaiDto
	 * @return
	 */
	@RequestMapping("do_save")
	public String doSave(HttpServletRequest request, Model model,JiedaiDto jiedaiDto){
		String res = "";
		try {
			jiedaiService.saveJiedai(jiedaiDto, model);
		} catch (Exception e) {
			log.error(e.getMessage());
			res = e.getMessage();
		}
		if(StringUtils.isNotBlank(res)){
			request.setAttribute("errorCode", res);
			return "su_error";
		}
		return "redirect:/jiedai/index.action";
	}
	
	/**
	 * 删除
	 * @param request
	 * @param model
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("destroy")
	public String destroy(HttpServletRequest request, Model model, HttpServletResponse response) {
		int jdId = SuIntUtils.getInt(request.getParameter("jdId"));
		try {
			jiedaiService.destroyJiedai(jdId);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/jiedai/index.action";
	}
	
	/**
	 * 导入Excel
	 * @param request
	 * @param response
	 * @param jiedaiDto
	 * @throws Exception
	 */
	@RequestMapping("importExcel")
    public void importExcel(HttpServletRequest request, HttpServletResponse response, JiedaiDto jiedaiDto) {
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		
        MultipartFile importExcelFile = jiedaiDto.getImportExcelFile();
        
        List<List<String[]>> list = ExcelUtil.getExcelContentFromMultipartFile(importExcelFile);
        if (list==null || list.isEmpty()) {
            out.println("请选择正确的Excel文件，excel请用2003或更高版本！");
            out.flush();
            return;
        }
        
        try {
        	jiedaiService.operateExcelData(list, out);
		} catch (Exception e) {
			out.println("导入数据异常，请检查excel文件或联系开发者");
		}
		
        out.flush();
    }
    
	/**
	 * 合计
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("to_count")
	public String count(HttpServletRequest request, Model model) throws Exception {
//		String year = request.getParameter("year");
//		if(StringUtils.isBlank(year))year="2012";
		List<Map<String,Object>>  jiedais = jiedaiService.getCountList(null);
		model.addAttribute("list", jiedais);
		return "/maintain/jiedai/jiedai_count";
	}

	/**
	 * 导出数据到excel中
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("exportDataToExcel")
    public void exportDataToExcel(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
        // 标头
        Map<String, String> titleMap = new LinkedHashMap<String, String>();
        titleMap.put("t1", "日期");
        titleMap.put("t2", "凭证字号");
        titleMap.put("t3", "摘要");
        titleMap.put("t4", "业务编号");
        titleMap.put("t5", "借方本位币金额");
        titleMap.put("t6", "贷方本位币金额");
        titleMap.put("t7", "余额方向");
        titleMap.put("t8", "本位币余额");
        
        // 查询目标数据
        List<Map<String,Object>>  jiedais = jiedaiService.getCountList(null);
        List<Map> dataMaps = new ArrayList<Map>();
        if(jiedais != null && !jiedais.isEmpty()){
        	Map<String,Object> dataMap,monthCount,yearCount;
        	JiedaiEntity jiedaiEntity;
        	for(Map<String,Object> jiedai : jiedais){
        		dataMap = new HashMap<String,Object>();
        		
        		if(jiedai.get("jdEntity") != null){//基本数据
        			jiedaiEntity = (JiedaiEntity)jiedai.get("jdEntity");
        			dataMap.put("t1", SuDateUtils.getFormatString(jiedaiEntity.getJdDate(), "yyyy-MM-dd"));
        			dataMap.put("t2", jiedaiEntity.getJdKey());
        			dataMap.put("t3", jiedaiEntity.getJdDesc());
        			dataMap.put("t4", jiedaiEntity.getJdCode());
        			dataMap.put("t5", SuDoubleUtils.double45(jiedaiEntity.getJdAmountJie(), 1));
        			dataMap.put("t6", SuDoubleUtils.double45(jiedaiEntity.getJdAmountDai(), 1));
        			dataMap.put("t7", jiedaiEntity.getJdTypeStr());
        			dataMap.put("t8", SuDoubleUtils.double45(jiedaiEntity.getJdBalance(), 1));
        		}
        		
        		if(jiedai.get("monthCount") != null){//月统计数据
        			monthCount = (Map<String,Object>)jiedai.get("monthCount");
        			dataMap.put("t1", SuDoubleUtils.double45((Double)monthCount.get("monthNum"), 0)+"月");
        			dataMap.put("t2", "");
        			dataMap.put("t3", "本期合计");
        			dataMap.put("t4", "");
        			dataMap.put("t5", SuDoubleUtils.double45((Double)monthCount.get("jieCount"), 1));
        			dataMap.put("t6", SuDoubleUtils.double45((Double)monthCount.get("daiCount"), 1));
        			dataMap.put("t7", "");
        			dataMap.put("t8", "");
        		}
        		
        		if(jiedai.get("yearCount") != null){//年统计数据
        			yearCount = (Map<String,Object>)jiedai.get("yearCount");
        			dataMap.put("t1", SuDoubleUtils.double45((Double)yearCount.get("monthNum"), 0)+"月");
        			dataMap.put("t2", "");
        			dataMap.put("t3", "本年累计");
        			dataMap.put("t4", "");
        			dataMap.put("t5", SuDoubleUtils.double45((Double)yearCount.get("jieCount"), 1));
        			dataMap.put("t6", SuDoubleUtils.double45((Double)yearCount.get("daiCount"), 1));
        			dataMap.put("t7", "");
        			dataMap.put("t8", "");
        		}
        		
        		dataMaps.add(dataMap);
        	}
        }
        
        
        ExcelUtil.exportDataToExcel(titleMap, dataMaps, request,response);

    }

	/**
	 * 全部删除
	 * @param request
	 * @param response
	 * @throws SQLException 
	 */
	@RequestMapping("removeAll")
    public void removeAll(HttpServletRequest request, HttpServletResponse response) throws SQLException {
		jiedaiService.removeAll();
    }
}

